package com.third.customer.service.utils;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hehuaichun on 2020/7/4.
 */
public abstract class TimeUtils {

    public static final String TIMEZONE_GMT8_NAME = "GMT+8";
    public static final ZoneId TIMEZONE_GMT8 = ZoneId.of(TIMEZONE_GMT8_NAME);
    public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final Map<String, DateTimeFormatter> DATE_TIME_FORMAT_MAP = new HashMap<String, DateTimeFormatter>() {
        {
            put(TIME_FORMAT, DateTimeFormatter.ofPattern(TIME_FORMAT));
        }
    };

    public static String dateToString(Date date) {
        return dateToString(date, TIME_FORMAT, TIMEZONE_GMT8);
    }

    /**
     * Date装换成String
     *
     * @param date   时间
     * @param format 转化格式
     * @return
     */
    public static String dateToString(Date date, String format, ZoneId zoneId) {
        DateTimeFormatter formatter = getDateTimeFormatter(format).withZone(zoneId);
        return formatter.format(date.toInstant());
    }

    /**
     * 根据format的格式获取相应的DateTimeFormatter对象
     *
     * @param format 时间转换格式字符串
     * @return
     */
    public static DateTimeFormatter getDateTimeFormatter(String format) {
        if (DATE_TIME_FORMAT_MAP.containsKey(format)) {
            return DATE_TIME_FORMAT_MAP.get(format);
        } else {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
            DATE_TIME_FORMAT_MAP.put(format, formatter);
            return formatter;
        }

    }

}
